<?php
/**
 * Created by PhpStorm.
 * Author: 芸签cms www.yunqiancms.com
 * User: sun
 * Date: 2022/6/23
 * Time: 1:49 PM
 */

use app\backend\modules\sys\services\PermissionService;
use app\common\helpers\Url;
use Illuminate\Support\Str;
use Illuminate\Support\Arr;


if (!function_exists('fmt_array_set')) {
    function fmt_array_set($array, $key, $value)
    {
        $keys = explode('.', $key);
        while (count($keys) > 1) {
            $key = array_shift($keys);

            // If the key doesn't exist at this depth, we will just create an empty array
            // to hold the next value, allowing us to create the arrays to hold final
            // values at the correct depth. Then we'll keep digging into the array.
            if (!isset($array[$key]) || !is_array($array[$key])) {
                $array[$key] = [];
            }
            $array = &$array[$key];
        }
        $array[array_shift($keys)] = $value;

        return $array;
    }
}
if (! function_exists('array_get')) {
    /**
     * Get an item from an array using "dot" notation.
     *
     * @param  \ArrayAccess|array  $array
     * @param  string|int  $key
     * @param  mixed  $default
     * @return mixed
     */
    function array_get($array, $key, $default = null)
    {
        return Arr::get($array, $key, $default);
    }
}
if (! function_exists('array_last')) {
    /**
     * Return the last element in an array passing a given truth test.
     *
     * @param  array  $array
     * @param  callable|null  $callback
     * @param  mixed  $default
     * @return mixed
     */
    function array_last($array, callable $callback = null, $default = null)
    {
        return Arr::last($array, $callback, $default);
    }
}
if (! function_exists('array_set')) {
    /**
     * Set an array item to a given value using "dot" notation.
     *
     * If no key is given to the method, the entire array will be replaced.
     *
     * @param  array  $array
     * @param  string  $key
     * @param  mixed  $value
     * @return array
     */
    function array_set(&$array, $key, $value)
    {
        return Arr::set($array, $key, $value);
    }
}
if (!function_exists('array_child_kv_exists')) {
    function array_child_kv_exists($array, $childKey, $value)
    {
        $result = false;

        if (is_array($array)) {
            foreach ($array as $v) {
                if (is_array($v) && isset($v[$childKey])) {
                    $result += $v[$childKey] == $value;
                }
            }
        }

        return $result;
    }
}
if (! function_exists('str_random')) {
    /**
     * Generate a more truly "random" alpha-numeric string.
     *
     * @param  int  $length
     * @return string
     *
     * @throws \RuntimeException
     */
    function str_random($length = 16)
    {
        return Str::random($length);
    }
}
if (!function_exists('rand_num')) {
    /**
     * 获取随机字符串
     * @param number $length 字符串长度
     * @param boolean $numeric 是否为纯数字
     * @return string
     */
    function rand_num($length, $numeric = FALSE) {
        $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
        $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
        if ($numeric) {
            $hash = '';
        } else {
            $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
            $length--;
        }
        $max = strlen($seed) - 1;
        for ($i = 0; $i < $length; $i++) {
            $hash .= $seed[mt_rand(0, $max)];
        }
        return $hash;
    }
}
if (!function_exists('safe_gpc_html')) {
    /**
     * 防止GPC引起的sql注入
     * @param $value
     * @param string $default
     * @return mixed|null|string|string[]
     */
    function safe_gpc_html($value, $default = '')
    {
        if (empty($value) || !is_string($value)) {
            return $default;
        }
        $value = safe_bad_str_replace($value);

        $value = safe_remove_xss($value);
        if (!$value && $value != $default) {
            $value = $default;
        }
        return $value;
    }
}
if (!function_exists('safe_bad_str_replace')) {
    /**
     * 转义敏感字符
     * @param $string
     * @return mixed|string
     */
    function safe_bad_str_replace($string)
    {
        if (!$string) {
            return '';
        }
        $badstr = array("\0", "%00", "%3C", "%3E", '<?', '<%', '<?php', '{php', '../');
        $newstr = array('_', '_', '&lt;', '&gt;', '_', '_', '_', '_', '.._');
        $string = str_replace($badstr, $newstr, $string);

        return $string;
    }
}
if (!function_exists('safe_remove_xss')) {
    /**
     * 防止xss注入
     * @param $val
     * @return mixed|null|string|string[]
     */
    function safe_remove_xss($val)
    {
        $val = preg_replace('/([\x0e-\x19])/', '', $val);
        $search = 'abcdefghijklmnopqrstuvwxyz';
        $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $search .= '1234567890!@#$%^&*()';
        $search .= '~`";:?+/={}[]-_|\'\\';

        for ($i = 0; $i < strlen($search); $i++) {
            $val = preg_replace('/(&#[xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val);
            $val = preg_replace('/(&#0{0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val);
        }
        preg_match_all('/href=[\'|\"](.*?)[\'|\"]|src=[\'|\"](.*?)[\'|\"]/i', $val, $matches);
        $url_list = array_merge($matches[1], $matches[2]);
        $encode_url_list = array();
        if ($url_list) {
            foreach ($url_list as $key => $url) {
                $val = str_replace($url, 'yq_' . $key . '_yqplaceholder', $val);
                $encode_url_list[] = $url;
            }
        }
        $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'script', 'embed', 'object', 'frameset', 'ilayer', 'bgsound', 'base');
        $ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload', '@import');
        $ra = array_merge($ra1, $ra2);
        $found = true;
        while ($found == true) {
            $val_before = $val;
            for ($i = 0; $i < sizeof($ra); $i++) {
                $pattern = '/';
                for ($j = 0; $j < strlen($ra[$i]); $j++) {
                    if ($j > 0) {
                        $pattern .= '(';
                        $pattern .= '(&#[xX]0{0,8}([9ab]);)';
                        $pattern .= '|';
                        $pattern .= '|(&#0{0,8}([9|10|13]);)';
                        $pattern .= ')*';
                    }
                    $pattern .= $ra[$i][$j];
                }
                $pattern .= '/i';
                $replacement = substr($ra[$i], 0, 2) . '<x>' . substr($ra[$i], 2);
                $val = preg_replace($pattern, $replacement, $val);
                if ($val_before == $val) {
                    $found = false;
                }
            }
        }
        if ($encode_url_list && is_array($encode_url_list)) {
            foreach ($encode_url_list as $key => $url) {
                $val = str_replace('yq_' . $key . '_yqplaceholder', $url, $val);
            }
        }
        return $val;
    }
}
if (!function_exists('fmt_media_url')) {
    /**
     * @param $src
     * @param bool $local_path
     * @param null $upload_type
     * @param string $host
     * @return string
     */
    function fmt_media_url($src, $local_path = false, $upload_type = null,$host = '')
    {
        if (empty($src)) {
            return '';
        }
        $HttpHost = request()->getSchemeAndHttpHost();
        if ($host) {
            $HttpHost = $host;
        }
        $setting = \app\common\facades\Setting::get('cms.remote_attach');

        $upload_type = $setting['type'];
        $attachment = '/static/upload/';
        $file_name = 'photo-mr';
        $file_path = public_path($attachment) . $src;\Log::debug('$file_path',$file_path);
        if (file_exists($file_path)) {//本地图片存在直接返回 示例图片path image/e3a555295b58e043dbf8ea3eb0434647.png
            //返回给前端不能带public路径
            return $HttpHost.$attachment . $src;
        }
        if (strexists($src, $attachment)) {//本地图片存在直接返回 示例图片path /static/upload/image/e3a555295b58e043dbf8ea3eb0434647.png
            //$relative_path不能带public
            $relative_path = substr($src, strpos($src, $attachment));
            $file_path = public_path($relative_path);
            if (file_exists($file_path)) {
                return $HttpHost.$relative_path;
            }
        }
        if (strexists($src, $file_name) && file_exists(public_path($src))) { //默认会员头像
            return $HttpHost.$src;
        }
        $local = strtolower($src);
        $attach_url_remote = '';
        if ($upload_type) {
            switch ($upload_type) {
                case \app\common\models\CoreAttach::UPLOAD_ALIOSS :
                    $attach_url_remote = $setting['alioss']['url'];
                    break;
                case \app\common\models\CoreAttach::UPLOAD_QCLOUDCOS :
                    $attach_url_remote = $setting['cos']['url'];
                    break;
            }
            if(!strexists($attach_url_remote,'http://')&&!strexists($attach_url_remote,'https://')){
                //如果url不包含http或https，统一设置https
                $attach_url_remote = 'https://'.$attach_url_remote;
            }
        }
        if (strexists($src, $HttpHost) && strexists($src, $attachment)  && $upload_type) {
            $host_str = $HttpHost.$attachment;
            $str_len = strlen($host_str);
            $relative_path = substr($src, $str_len);
            return $attach_url_remote .'/'. $relative_path;
        }
        //判断是否是本地不带域名图片地址
        if ((strexists($src, $attachment) && (parse_url($src)['scheme'].'://'.parse_url($src)['host']) == $HttpHost) || (strexists($src, $attachment) && !strexists($src, 'http://') && !strexists($src, 'https://'))) {
            return $HttpHost . substr($src, strpos($src, $attachment));
        }
        //如果远程地址中包含本地host也检测是否远程图片
        if (strexists($local, 'http://') || strexists($local, 'https://') || substr($local, 0, 2) == '//') {
            return 'https:' . substr($src, strpos($src, '//'));
        }
        if ($upload_type) {
            return $attach_url_remote.'/'.$src;
        }
        if (preg_match('/^(\/\/){1}.*/',$src)) {
            return $src;
        }
        if (!config('app.debug')) {
            $src = 'https:' . substr($src, strpos($src, '//'));
        }
        return $src;
    }
}
if (!function_exists('absolute_admin_url')) {
    /**
     * 后端绝对地址
     * @param $route
     * @param array $params
     * @return string
     */
    function absolute_admin_url($route, $params = [])
    {
        return Url::absoluteAdmin($route, $params);
    }
}
if (!function_exists('absolute_url')) {
    /**
     * 绝对地址
     * @param $route
     * @param array $params
     * @return string
     */
    function absolute_url($route)
    {
        return Url::absolute($route);
    }
}
if (!function_exists('file_remote_upload')) {
    /**
     * 远程上传文件
     * @param $filename
     * @param $remote
     * @param bool $auto_delete_local 自动删除
     * @throws \app\common\exceptions\BizException
     * @throws \OSS\Core\OssException
     */
    function file_remote_upload($filename, $remote,$auto_delete_local = true)
    {
        app\common\services\Upload::remote($filename,$remote);
        if ($auto_delete_local) {
            file_delete($filename);
        }
    }
}
if (!function_exists('file_remote_delete')) {
    function file_remote_delete($file,$remote)
    {
        app\common\services\Upload::remoteDelete($file,$remote);
    }
}
if (!function_exists('file_delete')) {
    function file_delete($file)
    {
        if (empty($file)) {
            return false;
        }
        if (file_exists($file)) {
            @unlink($file);
        }
        if (file_exists(public_path() . '/static/upload/' . $file)) {
            @unlink(public_path() . '/static/upload/' . $file);
        }

        return true;
    }
}
if (!function_exists("strexists")) {
    /**
     * 判断字符串是否包含子串
     * @param string $string 在该字符串中进行查找
     * @param string $find 需要查找的字符串
     * @return boolean
     */
    function strexists($string, $find)
    {
        return !(strpos($string, $find) === false);
    }
}
if (!function_exists('can')) {
    /**
     * 权限判断
     * @param $item   可以是item 或者是route
     * @return bool
     */
    function can($item)
    {
        /*if(config('app.menu_key') != 'menu'){
            return true;
        }*/
        return PermissionService::can($item);
    }
}
//按条件获取分类列表
function cms_category_list($params){
    return \app\common\models\Category::getListByCondition($params);
}
//按条件获取某个分类
function cms_category($params){
    return \app\common\models\Category::getFirstByCondition($params);
}
//按条件获取文章列表
function cms_article_list($params){
    return \app\common\models\Article::getListByCondition($params);
}
//前一篇文章
function cms_previous_article($id){
    return cms_article_list([
        'where'=>['id <'.$id],
        'order'=>'display_order desc,id desc',
        'limit'=>1
    ]);
}
//后一篇文章
function cms_next_article($id){
    return cms_article_list([
        'where'=>['id >'.$id],
        'order'=>'display_order desc,id desc',
        'limit'=>1
    ]);
}
//文章列表按树级形式显示
function cms_level_article_list($params){
    return (new \app\common\services\content\ArticleService())->getLevelList($params);
}